package com.hk.jmm.helper;

import com.hk.jmm.db.GreenDaoManager;

import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.annotations.NonNull;
import io.reactivex.rxjava3.core.Observable;
import io.reactivex.rxjava3.core.ObservableEmitter;
import io.reactivex.rxjava3.core.ObservableOnSubscribe;
import io.reactivex.rxjava3.core.Observer;
import io.reactivex.rxjava3.schedulers.Schedulers;

public class BaseHelper {

    public <T> void dbObservableRunInTx(Runnable runnable, Observer<T> observer,DbObservableRunInTxCallBack<T> callBack){
        Observable<T> observable = Observable.create(new ObservableOnSubscribe<T>() {
            @Override
            public void subscribe(@NonNull ObservableEmitter<T> emitter){
                try {
                    GreenDaoManager.getInstance().getNewSession().runInTx(runnable);
                    if (callBack!=null){
                        callBack.emitterNext(emitter);
                    }
                }catch (Exception e){
                    e.printStackTrace();
                    emitter.onError(e);
                }

            }
        });
        observable
                .subscribeOn(Schedulers.io())  // 在IO线程中执行
                .observeOn(AndroidSchedulers.mainThread())  // 在主线程中处理结果
                .subscribe(observer);
    }

    public interface DbObservableRunInTxCallBack<T>{
        void emitterNext(ObservableEmitter<T> emitter);

    }
}
